﻿using System;
using BestHTTP;
using BestHTTP.JSON.LitJson;
using BestHTTP.WebSocket;
using Constant;
using Framework;

public class VoiceRecognitionService : Service
{
    private WebSocket webSocket;

    private string address;

    const string ServerReady = "server_ready";
    const string FinalResult = "final_result";
    const string PartialResult = "partial_result";

    public override void Init()
    {
        Log.Warning("VoiceRecognitionService init");
    }

    public void SendStartSignal(string address)
    {
        this.address = address;

        webSocket = new WebSocket(new Uri(address));

#if !UNITY_WEBGL || UNITY_EDITOR
        webSocket.StartPingThread = true;

#if !BESTHTTP_DISABLE_PROXY
        if (HTTPManager.Proxy != null)
            webSocket.OnInternalRequestCreated = (ws, internalRequest) =>
                internalRequest.Proxy = new HTTPProxy(HTTPManager.Proxy.Address,
                    HTTPManager.Proxy.Credentials, false);
#endif
#endif

        webSocket.OnOpen += OnOpen;
        webSocket.OnMessage += OnMessageReceived;
        webSocket.OnClosed += OnClosed;
        webSocket.OnError += OnError;

        webSocket.Open();
    }

    private void OnOpen(WebSocket websocket)
    {
        webSocket.Send(CMD.StartSignal);
    }
    
    void SendEndSignal()
    {
        webSocket.Send(CMD.EndSignal);
    }

    void OnMessageReceived(WebSocket ws, string message)
    {
        Log.Debug($"WebSocket OnMessageReceived: {message}");

        JsonData jsonData = JsonMapper.ToObject(message);
        string type = (string) jsonData["type"];

        if (type == ServerReady)
        {
            Log.Debug(this.GetType() + " " + ServerReady);
        }
        else
        {
            if (type == FinalResult)
            {
                string nbest = (string) jsonData["nbest"];

                JsonData jsonDataNbest = JsonMapper.ToObject(nbest);
                if (jsonDataNbest.IsArray)
                {
                    // messageField.text = messageFieldText + (string) jsonDataNbest[0]["sentence"]; //最后的结果
                }
            }
            else
            {
                if (type == PartialResult)
                {
                    string nbest = (string) jsonData["nbest"];

                    JsonData jsonDataNbest = JsonMapper.ToObject(nbest);
                    if (jsonDataNbest.IsArray)
                    {
                        // messageField.text = messageFieldText + (string) jsonDataNbest[0]["sentence"]; //最后的结果
                    }
                }
            }
        }
    }

    /// <summary>
    /// Called when the web socket closed
    /// </summary>
    void OnClosed(WebSocket ws, UInt16 code, string message)
    {
        Log.Debug($"WebSocket closed! Code: {code} Message: {message}");

        webSocket = null;
    }

    /// <summary>
    /// Called when an error occured on client side
    /// </summary>
    void OnError(WebSocket ws, string error)
    {
        webSocket = null;
    }
}